<?php

namespace app\backstage\controller;
header("Content-type: text/html; charset=utf-8");

use think\Controller;
use think\Request;
use app\backstage\model\ResourceFile;
use app\backstage\model\ResourceFolder;
use Db;

class Resource extends Controller
{    


    /**
     * 显示图片文件夹
     *
     * @return \think\Response
     */
    public function image_folder(Request $request,ResourceFolder $resource)
    {

        $sel = $request->param('sel');

        return view('folder_list',['folder_type'=>1,'sel'=>$sel]);
    }

    /**
     * 获取文件夹列表
     *
     * @return \think\Response
     */
    public function folder_list(Request $request,ResourceFolder $resource)
    {


       if($type = $request->param('folder_type')){
          $data = $resource->field('id,folder_name')->where(['type'=>$type,'admin_id'=>$request->admin_id])->select();

          return ['code'=>200,'data'=>$data];
       }
    }


    /**
     * 创建文件夹
     *
     * @return \think\Response
     */
    public function create_folder($folder_type,Request $request,ResourceFolder $resource)
    {   


        if($folder_name = $request->post('folder_name')){

            $inData = array(
                'folder_name' => $folder_name,
                'type'        => $folder_type,
                'admin_id'    => $request->admin_id,
                'create_time' => time()
            );

            $in = $resource->insert($inData);

            if($in){
                return ['code'=>200];
            }else{
                return ['code'=>100,'msg'=>'创建失败'];
            }
        }

        return view('create_folder',['folder_type'=>$folder_type]);
    }

    /**
     * 删除文件夹
     */
    public function delete_folder(Request $request,ResourceFolder $resource,ResourceFile $file){

        if( $ids =  $request->param('ids')){

            

            Db::startTrans();
            $res = $resource->whereIn('id',$ids)->delete();
            
            if($res){

                $files = $file->whereIn('folder_id',$ids)->select();
                
                if(count($files)>0){
                    // dump($files);
                    //删除包含的文件
                    $res = $file->whereIn('folder_id',$ids)->delete();
                    foreach($files as $v){
//                        $v['file_path']=iconv('utf-8', 'gbk', $v['file_path']);
//                        if(file_exists('uploads/'.$v['file_path'])){
//                            unlink('uploads/'.$v['file_path']);
//                        }
                        //从云上删除
                        ossDeleteFile($v['file_path']);
                    }
                }

                if($res){
                    Db::commit();
                    return ['code'=>200];            
                }else{
                    Db::rollback();      
                    return ['code'=>100,'msg'=>'删除文件失败'];   
                }
               
            }else{
                return ['code'=>100,'msg'=>'删除失败'];
            
            }
          
        }else{
       
            return ['code'=>100,'msg'=>'参数有误'];
        }
    }

    /**
     * 修改文件夹名称
     */
    public function update_folder_name(Request $request,ResourceFolder $resource){
        
        if(  $request->param('id') &&  $request->param('folder_name')){

            $res = $resource->where('id',$request->param('id'))->update(['folder_name'=> $request->param('folder_name')]);

            return ['code'=>200];            
            
        }else{
        
            return ['code'=>100,'msg'=>'参数有误'];
        }
    }
    
    /**
     * 显示图片列表
     *
     * @return \think\Response
     */
    public function image_list(Request $request,ResourceFile $resource)
    {              


        if($request->isAjax()){
             //分页
             $pageSize = 15;
             $params = $request->param();
 
             $page = $params['page']?:1;
             $offset = ($page-1)*$pageSize;
             $where = [
                 ['admin_id','=',$request->admin_id],
                 ['folder_id','=',$params['folder_id']],

             ];
             //搜索
             if(!empty($params['start'])){
                 $where[] = ['create_time','>=',strtotime($params['start'])];
             }
 
             if(!empty($params['end'])){
                 $where[] = ['create_time','<=',strtotime($params['end'])];
             }
 
             if(!empty($params['seach_text'])){
                 $where[] = ['file_path','like',"%{$params['seach_text']}%"];
             }


             
             //图片列表
             $data = $resource->where($where)->order('id','desc')->limit($offset,$pageSize)->select();  
             
             $count = $resource->where($where)->count();
  
             $pageData = ['count'=>$count,'page'=>(int)$page,'pageSize'=>$pageSize];
             
             if($data){
                 foreach($data as &$v){
                     $v['create_time'] = date('Y-m-d H:i',$v['create_time']);
                     $v['file_path']  = $v['file_path'];
                    //  if(mb_strlen($v['file_name']>20)){
                    //      $v['file_name'] = mb_substr($v['file_name'],0,20).'...';
                    //  }
                 }
             }

             return ['code'=>200,'imageList'=>$data,'pageData'=>$pageData];
        }


        if($sel=$request->param('sel')){
            return view('image_select_list',['folder_id'=>$request->param('folder_id'),'sel'=>$sel]);
        }

        return view('image_list',['folder_id'=>$request->param('folder_id')]);
    }



    /**
     * 上传单张图片到阿里云oss
     *
     * @return \think\Response
     */
    public function upload_image(Request $request,ResourceFile $resource)
    {

        if($request->isPost()){


            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');

            $tmp_name = $file->getInfo()['tmp_name'];



            $fileName =$file->getInfo()['name'];

            // 移动到框架应用根目录/uploads/ 目录下
            $folder = 'house_images';

            $info = ossUploadFile($folder,$tmp_name);

            if($info){

                // 成功上传后 获取上传信息
                $insertData = array(
                    'file_name'=>$fileName,
                    'file_path'=>$info['file_name'],
                    'type'=>1,
                    'admin_id'=>$request->admin_id,
                    'folder_id' => $request->param('folder_id'),
                    'create_time' =>time()
                );

                $in = $resource->insert($insertData);

                if($in){
                    return ['code'=>200,'msg'=>'success','file_name'=>$fileName];
                }else{
//                    unlink('uploads/'.$filePath);
                    return ['code'=>100,'msg'=>'保存图片失败'];
            
                }

            }else{
                // 上传失败获取错误信息
                return ['code'=>200,'msg'=>$file->getError()];
                
            }

        }

        return view('show_upload_image',['folder_id'=>$request->param('folder_id'),'type'=>$request->param('type')]);
    }

    /**
     * 上传单张图片到本地
     *
     * @return \think\Response
     */
    public function upload_image_local(Request $request,ResourceFile $resource)
    {

        if($request->isPost()){

            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');

            $fileName =$file->getInfo()['name'];

            // 移动到框架应用根目录/uploads/ 目录下
            $fileName = date('His').'_'.$fileName;
            $filePath = date('Ymd').'/'.$fileName;
//            $info = $file->move( 'uploads', iconv('UTF-8','GBK//IGNORE',$filePath),false);
            $info = $file->move( 'uploads', $filePath,false);
            if($info){

                // 成功上传后 获取上传信息
                $insertData = array(
                    'file_name'=>$fileName,
                    'file_path'=>$filePath,
                    'type'=>1,
                    'admin_id'=>$request->admin_id,
                    'folder_id' => $request->param('folder_id'),
                    'create_time' =>time()
                );

                $in = $resource->insert($insertData);

                if($in){
                    return ['code'=>200,'msg'=>'success','file_name'=>$fileName];
                }else{
                    unlink('uploads/'.$filePath);
                    return ['code'=>100,'msg'=>'保存图片失败'];

                }

            }else{
                // 上传失败获取错误信息
                return ['code'=>200,'msg'=>$file->getError()];

            }

        }

        return view('show_upload_image',['folder_id'=>$request->param('folder_id'),'type'=>$request->param('type')]);
    }



    public function upload_image_all(){

    }
    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {   
     
        $res = ResourceFile::destroy($id);

        if($res){
            return ['code'=>200];
        }else{
            return ['code'=>101,'msg'=>'删除失败'];
        }
    }


      /**
     * 批量删除
     *
     * @param  string  $ids
     * @return \think\Response
     */
    public function delete_all()
    {   

        if($ids = request()->post('ids')){

            $files = ResourceFile::whereIn('id',$ids)->select();

            if($files){
                $res = ResourceFile::destroy($ids);
                
                foreach($files as $v){
//                    $v['file_path']=iconv('utf-8', 'gbk', $v['file_path']);
//                    if(file_exists('uploads/'.$v['file_path'])){
//                        unlink('uploads/'.$v['file_path']);
//                    }

                    //从云上删除
                   ossDeleteFile($v['file_path']);

                }
            }
          
            if($res){
                return ['code'=>200];
            }else{
                return ['code'=>101,'msg'=>'删除失败'];
            }
        }else{
            return ['code'=>101,'msg'=>'缺少参数'];
        }
      
    }
}
